const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');
require('dotenv').config({ path: '.env.local' });

async function setupDatabase() {
  console.log('🚀 开始设置数据库...');

  // 创建数据库连接（不指定数据库）
  const connection = await mysql.createConnection({
    host: process.env.MYSQL_HOST || 'localhost',
    port: parseInt(process.env.MYSQL_PORT) || 3306,
    user: process.env.MYSQL_USER || 'root',
    password: process.env.MYSQL_PASSWORD || '',
    multipleStatements: true,
  });

  try {
    // 创建数据库
    const dbName = process.env.MYSQL_DATABASE || 'alibaba_rag';
    console.log(`📦 创建数据库: ${dbName}`);

    await connection.query(
      `CREATE DATABASE IF NOT EXISTS \`${dbName}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`
    );
    await connection.query(`USE \`${dbName}\``);

    // 读取并执行SQL文件
    const sqlFile = path.join(__dirname, 'init-database.sql');
    let sqlContent = fs.readFileSync(sqlFile, 'utf8');

    // 移除CREATE DATABASE和USE语句，因为我们已经处理了
    sqlContent = sqlContent
      .replace(/CREATE DATABASE[^;]*;/gi, '')
      .replace(/USE[^;]*;/gi, '')
      .trim();

    console.log('📝 执行SQL文件...');

    try {
      await connection.query(sqlContent);
      console.log('✅ SQL文件执行成功');
    } catch (error) {
      console.error('❌ SQL执行错误:', error.message);
      throw error;
    }

    // 验证表是否创建成功
    const [tables] = await connection.query('SHOW TABLES');
    console.log('✅ 数据库表创建成功:');
    tables.forEach(table => {
      console.log(`   - ${Object.values(table)[0]}`);
    });

    console.log('🎉 数据库设置完成!');
  } catch (error) {
    console.error('❌ 数据库设置失败:', error.message);
    process.exit(1);
  } finally {
    await connection.end();
  }
}

// 测试数据库连接
async function testConnection() {
  console.log('🔍 测试数据库连接...');

  try {
    const connection = await mysql.createConnection({
      host: process.env.MYSQL_HOST || 'localhost',
      port: parseInt(process.env.MYSQL_PORT) || 3306,
      user: process.env.MYSQL_USER || 'root',
      password: process.env.MYSQL_PASSWORD || '',
      database: process.env.MYSQL_DATABASE || 'alibaba_rag',
    });

    const [result] = await connection.query('SELECT 1 as test');
    console.log('✅ 数据库连接成功!');

    await connection.end();
    return true;
  } catch (error) {
    console.error('❌ 数据库连接失败:', error.message);
    return false;
  }
}

// 主函数
async function main() {
  const args = process.argv.slice(2);

  if (args.includes('--test')) {
    await testConnection();
  } else {
    await setupDatabase();
    await testConnection();
  }
}

if (require.main === module) {
  main().catch(console.error);
}

module.exports = { setupDatabase, testConnection };
